package edu.wata.web.filter;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import edu.wata.dao.OnlineJdbcDaoImpl;
import edu.wata.dao.iface.OnlineDao;
import edu.wata.domain.Online;

@WebFilter(dispatcherTypes = { DispatcherType.REQUEST, DispatcherType.FORWARD }, urlPatterns = { "/user.servlet" })
public class UserBehaviorFilter implements Filter {

	private static Logger log = Logger.getLogger(UserBehaviorFilter.class);

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		chain.doFilter(req, response);

		OnlineDao onlineDao = new OnlineJdbcDaoImpl();
		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession session = request.getSession();
		if (Objects.equals("login", request.getParameter("param")) && null != session.getAttribute("name")) {
			Online ol = new Online(0, (String) session.getAttribute("name"), request.getRemoteAddr(), "",
					LocalDateTime.now());
			int rowNum = onlineDao.insertOnline(ol); // record user login time
			log.debug(rowNum);
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
